﻿using System;
using System.Threading.Tasks;
using Surf.GrpcInvoker.Demo.Core.Interceptors;

namespace Surf.GrpcInvoker.Demo.Core.CallHandlers
{
    internal class ServerCallHandler<TRequest, TResponse> : IServerCallHandler where TRequest : class where TResponse : class
    {
        readonly Method<TRequest, TResponse> _method;
        readonly ServerMethod<TRequest, TResponse> _handler;

        public ServerCallHandler(Method<TRequest, TResponse> method, ServerMethod<TRequest, TResponse> handler)
        {
            _method = method;
            _handler = handler;
        }

        public Task HandleCall(byte[] requestMessage)
        {
            var request = _method.RequestMarshaller.Deserializer(requestMessage);

            try
            {
                var response = _handler(request);
                return response;
            }
            catch (Exception ex)
            {
                // Todo Logger
                // Todo new Exception
                throw ex;
            }
        }

        // 实现拦截功能
        public IServerCallHandler Intercept(Interceptor interceptor)
        {
            return new ServerCallHandler<TRequest, TResponse>(_method, r => interceptor.ServerCallHandler(r, _handler));
        }
    }
}
